/*
 *  Copyright (C) 2010 Martin Haulrich <mwh.isv@cbs.dk> and Matthias Buch-Kromann <mbk.isv@cbs.dk>
 *
 *  This file is part of the IncrementalParser package.
 *
 *  The IncrementalParser program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.osdtsystem.incparser.features;

import gnu.trove.TIntFloatHashMap;
import gnu.trove.TIntFloatIterator;
import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;
import java.util.Arrays;

/**
 *
 * @author Matthias Buch-Kromann and Martin Haulrich
 */
public class FeatureVectorSparse extends AbstractFeatureVector implements Serializable {
    static int ids = 0;
    final int id;
    TIntFloatHashMap weights = new TIntFloatHashMap();
    
    public FeatureVectorSparse() {
        this.id = ids++;
    }

    public FeatureVectorSparse(int initialCapacity) {
        this();
        weights.ensureCapacity(initialCapacity);
    }
    
    public final float weight(int feature) {
        return weights.get(feature);
        //return weights.contains(feature)
        //    ? weights.get(feature)
        //    : 0;
    }

    public final void setWeight(int feature, float weight) {
        if (weight != 0)
            weights.put(feature, weight);
        else
            weights.remove(feature);
        //printDebug(feature,  weight);

    }

    void printDebug(int feature, float weight) {
        System.out.println("FVSparse[" + id +
                "]: " + feature + "=" + weight);
    }
    
    public final void addWeight(int feature, float weight) {
        weights.adjustOrPutValue(feature, weight, weight);
    }

    public final int features() {
        return weights.size();
    }

    public void addTo(float scalarThis, FeatureVector other) {
        //System.out.println("addTo[" + features() + ":" + other.features());
        TIntFloatIterator iterator = weights.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            other.addWeight(iterator.key(), iterator.value() * scalarThis);
        }
    }

    public void addTo(FeatureAggregator aggregator) {
        TIntFloatIterator iterator = weights.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            aggregator.addFeature(iterator.key(), iterator.value());
        }
    }

    public void toSet() {
        //System.out.println("addTo[" + features() + ":" + other.features());
        TIntFloatIterator iterator = weights.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            if (iterator.value() != 0)
                iterator.setValue(1);
        }
    }

    public FeatureVector multiply(float scalar) {
        FeatureVector result = this.clone();
        TIntFloatIterator iterator = weights.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            result.setWeight(iterator.key(), iterator.value() * scalar);
        }
        return result;
    }

    public FeatureVector add(FeatureVector other) {
        if (other.features() > features())
            return other.add(this);
        FeatureVector result = this.clone();
        other.addTo(1, result);
        return result;
    }
    
    public FeatureVector subtract(FeatureVector other) {
        FeatureVector result = this.clone();
        other.addTo(-1, result);
        return result;
    }

    public FeatureVector linearCombination(float scaleThis, float scaleOther, FeatureVector other) {
        if (other.features() > features())
            return other.linearCombination(scaleOther, scaleThis, this);
        FeatureVector result = multiply(scaleThis);
        other.addTo(scaleOther, result);
        return result;
    }

    public double innerProduct(FeatureVector other) {
        // The smallest feature vector makes the computation
        if (other.features() < features())
            return other.innerProduct(this);

        // Compute inner product
        double innerProduct = 0;
        TIntFloatIterator iterator = weights.iterator();
        while (iterator.hasNext()) {
            iterator.advance();
            innerProduct += iterator.value() * other.weight(iterator.key());
        }

        // Return result
        return innerProduct;
    }

    @Override
    public FeatureVectorSparse clone() {
        FeatureVectorSparse clone = (FeatureVectorSparse) super.clone();
        clone.weights = (TIntFloatHashMap) weights.clone();
        return clone;
    }

    public void clear() {
        weights.clear();
    }

    public void trimToSize() {
        weights.trimToSize();
    }

    public void writeToFile(Writer writer) throws IOException {
        writer.write("FeatureVectorSparse: " + id + "\n");
        int[] features = weights.keys();
        Arrays.sort(features);
        for (int feature : features) {
            float weight = weights.get(feature);
            if (weight != 0) {
                writer.write(feature + "=" + String.format("%6g", weight));
                writer.write("\n");
            }
        }
    }



}
